package top.ywlog.permission.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import top.ywlog.permission.common.RequestHolder;
import top.ywlog.permission.common.response.Result;
import top.ywlog.permission.common.response.ResultCode;
import top.ywlog.permission.model.SysUser;
import top.ywlog.permission.util.JsonUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: Durian
 * @date: 2020/10/21 21:52
 * @description:
 */
@Slf4j
@Order(6)
@WebFilter(filterName = "loginFilter", urlPatterns = "/sys/*",
        dispatcherTypes = {
                DispatcherType.REQUEST,
                DispatcherType.ASYNC,
                DispatcherType.FORWARD,
        })
public class LoginFilter implements Filter
{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
    {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        SysUser sysUser = (SysUser) request.getSession().getAttribute("user");
        if (sysUser == null)
        {
            log.info("用户未登录");
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(JsonUtils.obj2String(Result.fail(ResultCode.NO_LOGIN)));
            // 跳转登录页面
            // response.sendRedirect("login.html");
            return;
        }
        // 向RequestHolder类中放入当前请求的user和request
        RequestHolder.add(sysUser);
        RequestHolder.add(request);
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy()
    {

    }
}
